package com.ddm.withoutpaper.controller;

import java.io.IOException;

import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.preference.PreferenceManager;
import android.util.Log;

public class UIController {

	private static UIController INSTANCE;
	
	private static final String SERVER_URL = "http://192.168.42.147:8080/WIPService/";
	
private boolean authenticated;
	
	private String[] itemMenu;
	
	private String login;
	
	private boolean logged;
	
	private UIController() {
		
	}
	
	public static UIController getInstance() {
		if (INSTANCE == null) {
			INSTANCE = new UIController();
		}
		return INSTANCE;
	}
	
	public void setScreen(Context context, Class c) {
		Intent i = new Intent(context, c);
		i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
		context.startActivity(i);
	}
	
	public void setScreenUri(Context context, String action, Uri uri) {
		Intent i = new Intent(action, uri);
		context.startActivity(i);
	}
	
	public boolean login(String login, String senha) {
		//ir no servidor e fazer login
		String res = "";

		String url = SERVER_URL + "/LoginServlet?login="+login+"&senha="+senha;
		Log.d("[DroidApp]", "login = " + login + " | senha = " + senha);
		
		HttpClient httpclient = new DefaultHttpClient();
		
		HttpGet httpget = new HttpGet(url);
		
		try {
			ResponseHandler<String> responseHandler = new BasicResponseHandler();
			res = httpclient.execute(httpget, responseHandler);
			Log.d("[UIController]", res);
		} catch (ClientProtocolException e) {
			Log.e("[UIController]", e.getMessage());
		} catch (IOException e) {
			Log.e("[UIController]", e.getMessage());
		}
		
		parse(res);
		
		if (authenticated) {
			return true;
		} else {
			return false;
		}
		
	}

	private void parse(String res) {
		try {
			JSONObject resp = new JSONObject(res).getJSONObject("response");
			Log.d("[PARSER]", res);
			String valor = resp.getString("valor");
			// se valor ok, seta authenticacao
			if (valor.equals("OK")) {// se valor ok, extrai os itens
				authenticated = true;
				JSONArray itens = new JSONObject(res).getJSONArray("itens");
				itemMenu = new String[itens.length()-1];
				
				for (int i = 0; i < (itens.length()-1); i++) {
					JSONObject item = itens.getJSONObject(i);
					itemMenu[i] = item.getString("id");
				}
				
			} else {
				authenticated = false;
			}
			
			
		} catch (JSONException e) {
			e.printStackTrace();
		}
	}

	public String[] getItemMenu() {
		return itemMenu;
	}
	
	public boolean verificaLogin(Context context) {
		//instanciar a SharedPreferences
		SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
		login = prefs.getString("login", "");
		logged = prefs.getBoolean("logado", false);
		String items = prefs.getString("items", null);
		
		if (items != null) {
			itemMenu = items.split(",");
		}
		
		return logged;
	}
	
	public void registraLogin(Context context, String login) {
		SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
		SharedPreferences.Editor editor = prefs.edit();
		
		editor.putString("login", login);
		editor.putBoolean("logado", true);
		
		StringBuffer sb = new StringBuffer();
		for (String item : itemMenu) {
			sb.append(item +",");
		}
		editor.putString("items", sb.toString());
		
		editor.commit();
	}
	
	public boolean isLogged() {
		return logged;
	}

	public void setLogged(boolean logged) {
		this.logged = logged;
	}

	
	public String getLogin() {
		return login;
	}

	public void setLogin(String login) {
		this.login = login;
	}

	public void setItemMenu(String[] itemMenu) {
		this.itemMenu = itemMenu;
	}
	

}
